<template>
  <view>
    <view
      v-show="!showHehunPopup"
      class="main-container"
      style="background-color: #dd302c"
    >
      <!-- 顶部导航 -->
      <view class="nav-bar">
        <view class="nav-left" @tap="handleBack">
          <u-icon name="arrow-left" color="#FFF" size="20"></u-icon>
        </view>
        <view class="nav-title">人工智能易学大模型</view>
        <view class="nav-right" @tap="handleBack">
          <u-icon name="close" color="#FFF" size="20"></u-icon>
        </view>
      </view>
      <!-- 用户信息区 -->
      <view class="user-info-area">
        <view class="user-name-row">
          <text class="user-name">{{ userInfo.userName }}</text>
          <view class="user-action-buttons">
            <view class="action-button" @tap="handleBackHome">
              <image
                src="/static/images/icon-return.png"
                class="action-icon"
              ></image>
              <text class="action-text">重新测算</text>
            </view>
            <!-- <view class="action-button" @tap="handleReport">
              <image src="/static/images/icon-report.png" class="action-icon"></image>
              <text class="action-text">测算报告</text>
            </view> -->
          </view>
        </view>
        <!-- 天干地支信息 -->
        <view class="celestial-container">
          <view class="celestial-stems-branches">
            <view
              class="celestial-item"
              v-for="(item, index) in otherUserInfo.celestialItems"
              :key="index"
            >
              <view class="celestial-icon">{{ item.label }}</view>
              <text class="celestial-text">{{ item.value }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 功能卡片区域 -->
      <view class="function-cards">
        <view
          class="function-card"
          v-for="(card, index) in otherUserInfo.shishenCard"
          :key="index"
        >
          <view class="card-header">
            <view class="category-icon"></view>
            <text class="card-title">{{ card.label }}</text>
          </view>
          <view class="card-content">
            <text class="card-text">{{ card.value }}</text>
          </view>
        </view>
      </view>

      <view class="box-content">
        <view class="feature-section">
          <view class="tabs-container">
            <view class="tabs-row">
              <view
                v-for="(tab, index) in marriageResultInfo.result"
                :key="index"
                class="tab"
                :class="{ active: currentMarriageTab === index }"
                @tap="changeMarriageTab(index)"
              >
                {{ tab.name }}
                <view
                  class="tab-underline"
                  :class="{ active: currentMarriageTab === index }"
                ></view>
              </view>
            </view>
            <view class="tab-content">
              <view
                v-for="(item, index) in marriageResultInfo.result[
                  currentMarriageTab
                ].content"
                class="tab-item"
              >
                <view class="title-icon">
                  <view class="title-text">{{ item.title }}</view>
                </view>
                <view class="tab-item-content">{{ item.thinkContent }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 其他支付项目 - 只在未支付时显示 -->
      <view class="box-content" style="margin-bottom: 0" v-if="!getPayStatus('other', 4)">
        <view class="service-items">
          <view class="service-grid">
            <!-- 服务项目组件结构 -->
            <view
              v-for="(item, index) in pageData.serviceItems"
              :key="index"
              class="service-item"
              v-show="!getPayStatus('other', index)"
            >
              <!-- 普通项目：左中右布局 -->
              <template v-if="!item.isSpecial">
                <image
                  :src="'/static/images/' + item.image"
                  mode="aspectFit"
                  class="service-icon"
                ></image>
                <view class="service-info">
                  <text class="service-name">{{ item.name }}</text>
                  <text class="service-desc">{{ item.desc }}</text>
                </view>
                <view class="service-right">
                  <view class="service-price">
                    <text class="original-price"
                      >原价￥{{ item.original }}</text
                    >
                    <text class="price-value">{{ item.price }}</text>
                    <text class="price-unit">元</text>
                  </view>
                  <view
                    class="pay-now"
                    @tap="
                      createOrder({
                        goodsId: item.goodsId,
                        payAmount: item.price,
                        index,
                      })
                    "
                  >
                    <text>微信支付</text>
                  </view>
                </view>
              </template>
            </view>
          </view>
        </view>
        <!-- 功能介绍 -->
        <view class="prices-section"  >
          <view class="price-section">
            <view class="price-wrapper">
              <text class="original-price">总计￥{{ originalPrice }}</text>
              <text class="current-price">优惠价：{{ currentPrice }}元</text>
            </view>
          </view>
          <!-- 支付按钮 -->
          <view class="pay-button" @tap="createOrder({goodsId: '20250618007', payAmount: '29', index:4,})">
            <text class="button-text">{{ pageData.payButton.text }}</text>
          </view>
          <view class="user-count"
            >已有
            <span style="color: #dd302c">{{
              Math.floor(userCount * 0.64)
            }}</span
            >人完成支付，获取了姻缘分析结果
          </view>
          <view class="otherComp-image">
            <image :src="pageData.feature.otherComp" mode="aspectFit"></image>
          </view>
        </view>
      </view>

      <!-- 底部信息 -->
      <view class="footer-info">
        <text class="sub-text"
          >本站所有测试项目，均由AI大模型根据传统易学八字自动测算，如有雷同，纯属巧合。测算结果不作为您真正的人生指导策划，仅作娱乐参考!某些民俗占卜，仅作研究之用，请勿迷信!</text
        >
      </view>

      <view class="footer-buttons-container">
        <view
          v-if="!getPayStatus('other', 4)"
          class="footer-button2"
          @tap="createOrder({goodsId: '20250618007', payAmount: '29', index:4,})"
        >
          测测其他运势
        </view>
        <view
          v-if="!getPayStatus('hehun')"
          class="footer-button2"
          @tap="handleHehun"
        >
          八字合婚
        </view>
      </view>

      <!-- 吸底按钮 -->
      <view class="fixed-buttons" :class="{ hidden: !showFixedButtons }">
        <view
          v-if="!getPayStatus('other', 4)"
          class="fixed-button"
          @tap="createOrder({goodsId: '20250618007', payAmount: '29', index:4,})"
        >
          测测其他运势
        </view>
        <view
          v-if="!getPayStatus('hehun')"
          class="fixed-button"
          @tap="handleHehun"
        >
          八字合婚
        </view>
      </view>
    </view>

    <!-- 底部固定按钮 -->

    <hehun-popup
      ref="hehunPopup"
      :visible="showHehunPopup"
      @close="showHehunPopup = false"
      @confirm="handleHehunConfirm"
    >
    </hehun-popup>
    <!-- 客服助手 -->
    <floating-image ref="floatingImage" />
    <floating-report ref="report" />
    <!-- <pay-status-dialog :visible="showPayStatusDialog" @confirm="confirmPayment" @retry="createOrder" /> -->
  </view>
</template>

<script>
import { getOtherInfo, queryOrder } from "@/api/fortune";
// import PayStatusDialog from '@/components/dialog/PayStatusDialog.vue';
import { trackButton, trackPageView, trackPayment } from "@/utils/track";
import { mapActions, mapGetters } from "vuex";
import HehunPopup from "../hehun/hehun-popup";
import pageData from "./data.js";
export default {
  name: "PayPage",
  components: {
    HehunPopup,
    // PayStatusDialog
  },
  data() {
    return {
      // 引用页面数据
      pageData,
      // 当前选中的婚姻透视tab
      currentMarriageTab: 0,
      // 价格相关
      originalPrice: pageData.price.original,
      currentPrice: pageData.price.current,
      // 合婚弹窗控制
      showHehunPopup: false,
      pageViewTracker: null,
      // 吸底按钮控制
      showFixedButtons: true,
      lastScrollTop: 0,
      showPayStatusDialog: false, // 支付状态弹窗
      currentorderNo: "", // 当前支付订单号
      payIndex: 0,
    };
  },
  computed: {
    ...mapGetters("fortune", [
      "userInfo",
      "otherUserInfo",
      "marriageResultInfo",
    ]),
    ...mapGetters("system", ["userCount"]),
    ...mapGetters("payment", ["getPayStatus"]),
  },
  mounted() {
    // 数据加载完成后显示悬浮图片
    this.$nextTick(() => {
      this.$refs.floatingImage.show();
    });
    // 启动页面浏览埋点计时
    this.pageViewTracker = trackPageView({
      reportKey: "进入姻缘测算详情页",
      reportVal: "浏览",
      pageName: "姻缘测算详情页",
    });
    this.pageViewTracker.start();

    // 添加滚动监听来控制吸底按钮显示
    window.addEventListener("scroll", this.handleScroll);
  },
  onHide() {
    // 页面离开时停止计时
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },
  onUnload() {
    // 页面卸载时也停止计时
    if (this.pageViewTracker) this.pageViewTracker.stop();
    // 卸载滚动监听
    window.removeEventListener("scroll", this.handleScroll);
  },
  onShow() {
    // this.$show.showToast(window.location.hash);
    const decodedOrderNo = this.$utils.getDecodedUrlParam("orderNo");
    const decodedType = this.$utils.getDecodedUrlParam("type");
    const decodedIndex = this.$utils.getDecodedUrlParam("index");

    if (decodedOrderNo && decodedType) {
      // 清除URL参数中的orderNo和type，避免重复处理
      const newUrl = window.location.pathname;
      window.history.replaceState({}, document.title, newUrl);
      this.currentorderNo = decodedOrderNo;
      this.payIndex = decodedIndex || 0;
      if (decodedType === "hehun") {
        this.showHehunPopup = true;
        this.$nextTick(() => {
          this.$refs.hehunPopup.handlePaymentSuccess(decodedOrderNo);
        });
      } else {
        this.confirmPayment();
      }
    }
  },
  methods: {
    ...mapActions("fortune", ["setOtherResultInfo"]),
    // 处理滚动事件，控制吸底按钮的显示和隐藏
    handleScroll() {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;

      // 获取其他支付项目区域元素
      const otherPaySection = document.querySelector(".service-items");

      if (otherPaySection) {
        // 获取元素在视口中的位置
        const otherPayRect = otherPaySection.getBoundingClientRect();
        const windowHeight = window.innerHeight;

        // 如果其他支付项目区域出现在视口中（顶部已进入视口或底部已进入视口）
        if (otherPayRect.top < windowHeight && otherPayRect.bottom > 0) {
          // 其他支付项目区域可见，隐藏吸底按钮
          this.showFixedButtons = false;
        } else {
          // 其他支付项目区域不可见，显示吸底按钮
          this.showFixedButtons = true;
        }
      } else {
        // 如果不存在其他支付项目区域（比如已经支付过），则使用原来的滚动逻辑
        // 获取婚姻透视区域元素
        const featureSection = document.querySelector(".feature-section");
        if (!featureSection) return;

        // 获取婚姻透视区域的底部位置
        const featureSectionBottom =
          featureSection.getBoundingClientRect().bottom + scrollTop;

        // 只有滚动超过婚姻透视区域后才考虑隐藏按钮
        if (scrollTop > featureSectionBottom) {
          // 向下滚动隐藏按钮，向上滚动显示按钮
          if (scrollTop > this.lastScrollTop) {
            this.showFixedButtons = false;
          } else {
            this.showFixedButtons = true;
          }
        } else {
          // 在婚姻透视区域内，总是显示按钮
          this.showFixedButtons = true;
        }
      }

      // 当页面快滚动到底部时，总是隐藏按钮
      const documentHeight = document.documentElement.scrollHeight;
      const windowHeight = window.innerHeight;
      if (documentHeight - (scrollTop + windowHeight) < 100) {
        this.showFixedButtons = false;
      }

      this.lastScrollTop = scrollTop;
    },
    // 切换婚姻透视tab
    changeMarriageTab(index) {
      this.currentMarriageTab = index;
    },
    // 处理返回和关闭
    handleBack() {
      uni.navigateTo({
        url: "/pages/payResult/report",
      });
    },
    handleBackHome() {
      // 重置所有支付状态
      this.$store.dispatch("payment/resetPayStatus");
      uni.reLaunch({
        url: "/pages/home/index",
      });
    },
    // handleReport() {
    //   uni.navigateTo({
    //     url: "/pages/payResult/report",
    //   });
    // },
    createOrder(param) {
      trackButton({
        reportKey: "测测其他运势按钮",
        reportVal: "跳转页面",
        pageName: "姻缘测算详情页",
      });
      this.payIndex = param.index || 0;
      uni.showLoading({ title: "正在创建订单...", mask: true });
      const orderParams = {
        goodsId: param.goodsId,
        payAmount: param.payAmount,
        redirect: "/pages/payResult/result",
        type: "other",
        index: param.index,
      };

      this.$commonPay(orderParams);
      uni.hideLoading();
    },
    confirmPayment() {
      uni.showLoading({ title: pageData.payMessages.loading, mask: true });
      this.verifyPaymentStatus(this.currentorderNo, async (success) => {
        uni.hideLoading();
        if (success) {
          // 支付验证成功
          try {
            const res = await getOtherInfo();
            this.$show.showToast(res.data);

            this.setOtherResultInfo(res.data);
            trackPayment({
              reportKey: "支付成功",
              reportVal: this.currentorderNo,
              pageName: "姻缘测算详情页",
            });
            this.$store.dispatch("payment/setPayStatus", {
              type: "other",
              status: true,
              index: this.payIndex,
            });
            this.$show.showToast(pageData.payMessages.success, {
              icon: "success",
              success: () => {
                uni.navigateTo({
                  url: `/pages/payResult/otherPay?index=${
                    this.payIndex == 4 ? 0 : this.payIndex
                  }`,
                });
              },
            });
          } catch (e) {
            console.log(e);
            this.$show.showToast(e);
          }
        } else {
          // 支付验证失败
          // this.showPayStatusDialog = true;
          this.$show.showToast(pageData.payMessages.failure, { icon: "error" });
          trackPayment({
            reportKey: "支付失败",
            reportVal: this.currentorderNo,
            pageName: "姻缘测算详情页",
          });
        }
      });
    },
    verifyPaymentStatus(orderNo, callback) {
      queryOrder(orderNo)
        .then((res) => {
          if (res.code === 0 && res.data && res.data.orderPayStatus === 1) {
            callback(true);
          } else {
            callback(false);
          }
        })
        .catch((err) => {
          console.error(pageData.payMessages.failure, err);
          callback(false);
        });
    },
    handleHehun() {
      trackButton({
        reportKey: "八字合婚按钮",
        reportVal: "跳转页面",
        pageName: "姻缘测算详情页",
      });
      if (!this.getPayStatus("hehun")) {
        this.showHehunPopup = true;
        return;
      } else {
        uni.navigateTo({
          url: "/pages/hehun/index",
        });
      }
    },
    // 处理合婚确认 - 执行跳转
    handleHehunConfirm() {
      // 隐藏弹窗
      this.showHehunPopup = false;
      setTimeout(() => {
        this.$show.showToast(pageData.payMessages.success, {
          icon: "success",
          success: () => {
            // 支付成功后跳转到合婚结果页面
            uni.navigateTo({
              url: "/pages/hehun/index",
            });
          },
        });
      }, 500);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./result.scss";
</style>
